package net.thxjj.mobileServer.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import net.thxjj.mobileServer.service.IUserService;

import java.util.logging.Logger;

public abstract class HeartBeatBaseChannelInBoundHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private Logger log = Logger.getLogger(String.valueOf(this.getClass()));

    private int lossConnectCount = 0;

    protected IUserService userService;

    public HeartBeatBaseChannelInBoundHandler() {

    }

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }


    public abstract void chanelReadR(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame s);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame s) throws Exception {
        lossConnectCount = 0;
        chanelReadR(channelHandlerContext,s);
       //this.channelRead(channelHandlerContext,s.text());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("已经"+lossConnectCount+"秒未收到客户端的消息了！");
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state()== IdleState.READER_IDLE){
                lossConnectCount++;
                if (lossConnectCount>100){
                    log.info("关闭这个不活跃通道！");
                    ctx.close();
                    AppSocketMap.removeSocketUser(ctx.channel());
                }
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
         super.channelRead(ctx,msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        AppSocketMap.removeSocketUser(ctx.channel());
    }
}
